package com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.manager.dict.dictionary;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.MutiModule.common.myPage.MyPageView;
import com.MutiModule.common.twitter.IDGenerator.instance.IdWorkerInstance;
import com.MutiModule.common.utils.DateUtils;
import com.MutiModule.common.utils.JSONUtilss;
import com.MutiModule.common.utils.StringUtilss;
import com.MutiModule.common.vo.ZTreeNodes;
import com.MutiModule.common.vo.enums.DeleteFlagEnum;
import com.MutiModule.common.vo.mybatis.pagination.Page;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.dict.dictionary.read.IDictDictionaryReadService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.dict.dictionary.write.IDictDictionaryWriteService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.base.BaseController;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.dict.dictionary.DictDictionary;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.dict.dictionary.view.DictDictionaryItemWithOutPrefixIdView;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.dict.dictionary.view.DictDictionaryWithItemView;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.dict.dictionary.view.DictDictionaryWithZtreeNodeView;
import com.alibaba.dubbo.config.annotation.Reference;

@Controller
@RequestMapping(value = "manager/dict/dictionary")
public class DictDictionaryController extends BaseController<DictDictionary>{

	@Reference(group="readService", interfaceName="com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.dict.dictionary.read.IDictDictionaryReadService")
	private IDictDictionaryReadService readService;
	
	@Reference(group="writeService", interfaceName="com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.dict.dictionary.write.IDictDictionaryWriteService")
	private IDictDictionaryWriteService writeService;

	@Override
	public ModelAndView list(ModelAndView model, HttpServletRequest request) {
		
		super.list(model, request);
		
		MyPageView<DictDictionary> pageView = decorateCondition(request);

		model.addObject("pageView", pageView);
		
		return model;
		
	}
	
	/**
	 * 封装参数部分
	 * @param request
	 * @return
	 */
	protected MyPageView<DictDictionary> decorateCondition(HttpServletRequest request) {
		
		String currentPageStr = request.getParameter("currentPage");
		if(StringUtilss.isEmpty(currentPageStr)) {
			currentPageStr = "1";
		}
		
		String recordPerPageStr = request.getParameter("recordPerPage");
		if(StringUtilss.isEmpty(recordPerPageStr)) {
			recordPerPageStr = "10";
		}

		int beginInt = Integer.parseInt(currentPageStr) >=1 ? Integer.parseInt(currentPageStr) : 1;
		
		Page page = new Page((beginInt - 1)*Integer.parseInt(recordPerPageStr), Integer.parseInt(recordPerPageStr));
		
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("page", page);
		
		//TODO 搜索条件添加
		String listSearchNameStr = request.getParameter("listSearchName");
		if(StringUtilss.isNotEmpty(listSearchNameStr)) {
			map.put("listSearchName", "%" + listSearchNameStr + "%");
		}
		
		MyPageView<DictDictionary> pageView = readService.generateMyPageViewVO(map);
		
		return pageView;
	}
	
	@Override
	public ModelAndView add(ModelAndView model, HttpServletRequest request) {
		
		super.add(model, request);
		return model;
		
	}
	
	/**
	 * 保存
	 * 
	 * @return
	 * @throws IOException
	 */
	@Override
	public ModelAndView doSave(ModelAndView model, HttpServletRequest request, DictDictionary entity, RedirectAttributesModelMap modelMap) throws Exception  {
		super.doSave(model, request, entity, modelMap);
		
		beforeDoSave(request, entity);
		writeService.insert(entity);
		afterDoSave(request, entity);
		model.setViewName("redirect:list");

		return model;
	}

	/**
	 * 调用保存方法之前进行的方法调用
	 * @param request
	 * @param entity 对应实体信息
	 * @throws Exception
	 */
	protected void beforeDoSave(HttpServletRequest request, DictDictionary entity) throws Exception {
		entity.setId(IdWorkerInstance.getIdStr());
		entity.setDeleteFlag(DeleteFlagEnum.NORMAL);
		entity.setCreateTime(DateUtils.getGMTBasicTime());
	}
	
	/**
	 * 电泳保存方法之后进行的方法调用
	 * @param request
	 * @param entity 对应实体信息
	 * @throws Exception
	 */
	protected void afterDoSave(HttpServletRequest request, DictDictionary entity) throws Exception {
		
	}
	
	@Override
	public ModelAndView doUpdate(ModelAndView model, HttpServletRequest request, DictDictionary entity, RedirectAttributesModelMap modelMap) throws Exception {
		super.doUpdate(model, request, entity, modelMap);
		
		beforeDoUpdate(request, entity);
		writeService.updateByPrimaryKeySelective(entity);
		afterDoUpdate(request, entity);
		model.setViewName("redirect:list");

		return model;
	}
	
	/**
	 * 调用更新操作之前进行的操作
	 * @param request
	 * @param entity
	 * @throws Exception
	 */
	protected void beforeDoUpdate(HttpServletRequest request, DictDictionary entity) throws Exception {
		
	}
	
	/**
	 * 调用更新操作之后进行的操作
	 * @param request
	 * @param entity
	 * @throws Exception
	 */
	protected void afterDoUpdate(HttpServletRequest request, DictDictionary entity) throws Exception {
		
	}
	
	@Override
	public ModelAndView show(@PathVariable("id") String id, ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", id);
		List<DictDictionaryWithZtreeNodeView> list = readService.selectDictionaryWithZTreeNodesListByMap(map);
		if(list != null && list.size() > 0) {
			model.addObject("dictDictionaryWithItemView", list.get(0));
			
			List<ZTreeNodes> zTreeNodesList = list.get(0).getzTreeNodess();
			if(zTreeNodesList != null && zTreeNodesList.size() > 0) {
				if(zTreeNodesList.size() == 1 && zTreeNodesList.get(0).getId() == null) {
					model.addObject("zNodes", "[]");
				} else {
					model.addObject("zNodes", JSONUtilss.toJSon(zTreeNodesList));
				}
			}
			
		}
		
		super.show(id, model, request, modelMap);
		
		return model;
	}
	
	@Override
	public ModelAndView edit(@PathVariable("id") String id, ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", id);
		List<DictDictionaryWithZtreeNodeView> list = readService.selectDictionaryWithZTreeNodesListByMap(map);
		if(list != null && list.size() > 0) {
			model.addObject("dictDictionaryWithItemView", list.get(0));
			List<ZTreeNodes> zTreeNodesList = list.get(0).getzTreeNodess();
			if(zTreeNodesList.size() == 1 && zTreeNodesList.get(0).getId() == null) {
				model.addObject("zNodes", "[]");
			} else {
				model.addObject("zNodes", JSONUtilss.toJSon(zTreeNodesList));
			}
			
			Long maxExistingZTreeNodesNum = 101L;
			List<ZTreeNodes> _zTreeNodesList = list.get(0).getzTreeNodess();
			if(_zTreeNodesList != null && _zTreeNodesList.size() > 0) {
				for (ZTreeNodes zTreeNodes : _zTreeNodesList) {
					if(zTreeNodes.getId() != null) {
						if(zTreeNodes.getId().compareTo(maxExistingZTreeNodesNum) >= 0 ) {
							maxExistingZTreeNodesNum = zTreeNodes.getId();
						}
					}
				}
			}
			model.addObject("maxExistingZTreeNodesNum", maxExistingZTreeNodesNum);
		}
		
		
		super.edit(id, model, request, modelMap);
		
		return model;
	}
	
	/**
	 * 保存
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/doSaveView")
	public ModelAndView doSaveView(ModelAndView model, HttpServletRequest request) throws Exception  {
		// 字典表 主表ID
		String dictDictionaryId = IdWorkerInstance.getIdStr();
		
		String _nodes = request.getParameter("_nodes");
		ZTreeNodes[] _nodesArray = JSONUtilss.readValue(_nodes, ZTreeNodes[].class);
		
		String type = request.getParameter("type");
		String perfixCode = request.getParameter("perfixCode");
		String content = request.getParameter("content");
		
		DictDictionaryWithItemView dictDictionaryView = new DictDictionaryWithItemView();
		dictDictionaryView.setId(dictDictionaryId);
		dictDictionaryView.setCreateTime(DateUtils.getGMTBasicTime());
		dictDictionaryView.setDeleteFlag(DeleteFlagEnum.NORMAL);
		dictDictionaryView.setType(type);
		dictDictionaryView.setPerfixCode(perfixCode);
		dictDictionaryView.setContent(content);
		
		List<DictDictionaryItemWithOutPrefixIdView> items = new ArrayList<DictDictionaryItemWithOutPrefixIdView>();
		for (int i = 0; i < _nodesArray.length; i++) {
			DictDictionaryItemWithOutPrefixIdView _item = new DictDictionaryItemWithOutPrefixIdView();
			_item.setId(perfixCode + _nodesArray[i].getId());
			_item.setReadId(_nodesArray[i].getId() + "");
			_item.setCreateTime(DateUtils.getGMTBasicTime());
			_item.setDeleteFlag(DeleteFlagEnum.NORMAL);
			_item.setContent(_nodesArray[i].getName());
			_item.setDictId(dictDictionaryId);
			if(_nodesArray[i].getpId() != null && StringUtilss.isNotEmpty(_nodesArray[i].getpId() + "")) {
				_item.setParentId(perfixCode + _nodesArray[i].getpId());
			}
			items.add(_item);
		}
		dictDictionaryView.setItems(items);
		
		writeService.insertDictDictionaryView(dictDictionaryView);
		
		model.setViewName("redirect:list");

		return model;
	}
	
	/**
	 * 保存
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/doUpdateView")
	public ModelAndView doUpdateView(ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		
		String _nodes = request.getParameter("_nodes");
		ZTreeNodes[] _nodesArray = JSONUtilss.readValue(_nodes, ZTreeNodes[].class);
		
		String dictDictionaryId = request.getParameter("dictDictionaryId");
		String type = request.getParameter("type");
		String perfixCode = request.getParameter("perfixCode");
		String content = request.getParameter("content");
		
		DictDictionaryWithItemView dictDictionaryView = new DictDictionaryWithItemView();
		dictDictionaryView.setId(dictDictionaryId);
		dictDictionaryView.setCreateTime(DateUtils.getGMTBasicTime());
		dictDictionaryView.setDeleteFlag(DeleteFlagEnum.NORMAL);
		dictDictionaryView.setType(type);
		dictDictionaryView.setPerfixCode(perfixCode);
		dictDictionaryView.setContent(content);
		
		List<DictDictionaryItemWithOutPrefixIdView> items = new ArrayList<DictDictionaryItemWithOutPrefixIdView>();
		for (int i = 0; i < _nodesArray.length; i++) {
			DictDictionaryItemWithOutPrefixIdView _item = new DictDictionaryItemWithOutPrefixIdView();
			_item.setId(perfixCode + _nodesArray[i].getId());
			_item.setReadId(_nodesArray[i].getId() + "");
			_item.setCreateTime(DateUtils.getGMTBasicTime());
			_item.setDeleteFlag(DeleteFlagEnum.NORMAL);
			_item.setContent(_nodesArray[i].getName());
			_item.setDictId(dictDictionaryId);
			if(_nodesArray[i].getpId() != null && StringUtilss.isNotEmpty(_nodesArray[i].getpId() + "")) {
				_item.setParentId(perfixCode + _nodesArray[i].getpId());
			}
			items.add(_item);
		}
		dictDictionaryView.setItems(items);
		
		writeService.updateDictDictionaryView(dictDictionaryView);
		
		String currentPageStr = request.getParameter("currentPage");
		if(StringUtilss.isEmpty(currentPageStr)) {
			currentPageStr = "1";
		}
		
		String recordPerPageStr = request.getParameter("recordPerPage");
		if(StringUtilss.isEmpty(recordPerPageStr)) {
			recordPerPageStr = "10";
		}
		modelMap.addAttribute("currentPage", currentPageStr);
		modelMap.addAttribute("recordPerPage", recordPerPageStr);
		
		model.setViewName("redirect:list");

		return model;
	}
}
